import React, { useEffect, useState } from 'react';
import { FullscreenOutlined, DeleteFilled, SearchOutlined, RedoOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Button, Input, Table, Space, Switch, Radio, Drawer, Select, Form, DatePicker, notification } from 'antd';
import type { RadioChangeEvent } from 'antd';
import './Region.scss'
import { formatDate } from '../../../../utils/timer';
import * as service from '../../../../api/index'
import _ from 'lodash'
//区域管理
const Region = () => {

    const { Search, TextArea } = Input
    const [mode, setMode] = useState('全部');
    const [loading, setLoading] = useState(false)
    const [time, setTime] = useState('')
    const [form] = Form.useForm()//获取form引用
    const [open, setOpen] = useState(false);
    const [data, setData] = useState([])
    const [areaId, setAreaId] = useState('')
    const [current, setCurrent] = useState(1)
    const [pagesize, stePagesize] = useState(10)
    const [totals, setTotals] = useState(0)


    //分页查询
    var query = async (current:any,pagesize:any) => {
        setLoading(true)
        var res = await service.default.wy.queryAll({ cp:current, ps:pagesize })
        if (res.data.code == 200) {
            setLoading(false)
            setTotals(res.data.count)
            setData(res.data.data.data)
        }
    }
    //修改单个数据状态的方法
    var changeFlag = async (areaId: any, status: any) => {
        var res = await service.default.wy.changeStatus(areaId, status)
        if (res.data.code == 200) {
            notification.success({
                message: '提示',
                description: '修改状态成功',
            });
            var table = _.cloneDeep(data)
            var item: any = table.find((item: any) => item.areaId == areaId)
            if (item) {
                item.status = status
            }
            setData(table)
        }
    }
    //根据状态查询数据
    var flag = async (status: number) => {
        setLoading(true)
        var res = await service.default.wy.data_queryStatus(status)
        if (res.data.code == 200) {
            setLoading(false)
            setData(res.data.data)
        } else {
            setLoading(false)
            notification.success({
                message: '提示',
                description: '当前状态数据为空',
            });
            setData([])
        }

    }
    //修改启用状态
    var handleChangeStatus = (record: any) => {
        if (record.status == 0) {
            record.status = 1
            changeFlag(record.areaId, record.status)
        } else {
            record.status = 0
            changeFlag(record.areaId, record.status)
        }

    }
    useEffect(() => {
        query(current,pagesize)
    }, [])
    //根据关键字进行查询
    const onSearch = async (e: any) => {
        setLoading(true)
        var res = await service.default.wy.data_queryKey(e)
        if (res.data.code == 200) {
            setLoading(false)
            setData(res.data.data)
        } else {
            setLoading(false)
            notification.error({
                message: '提示',
                description: '请输入正确的区域名称',
            });
        }
    }
    //根据状态查询数据
    const handleModeChange = async (e: RadioChangeEvent) => {
        setMode(e.target.value);
        if (e.target.value == '启用') {
            flag(0)
        } else if (e.target.value == '禁用') {
            flag(1)
        } else {
            query(current,pagesize)
        }

    };
    const columns = [
        {
            title: '操作',
            width: 120,
            key: '1',
            render: (record: any) => (
                <Space size="middle">
                    <Button size='small' onClick={() => handleDelete(record)} icon={<DeleteOutlined />}></Button>
                    <Button size='small' onClick={() => handleEdit(record)} icon={<EditOutlined />}></Button>
                    {/* <Button onClick={() => handleSearch(record)} icon={<SearchOutlined />}></Button> */}
                </Space>
            )
        },
        {
            title: '区域名称',
            width: 180,
            dataIndex: 'areaName',
            key: '2',
        },
        {
            title: '状态',
            width: 180,
            key: '3',
            render: (record: any) => (
                <Space size="middle">
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" checked={record.status == 1 ? false : true} onChange={() => handleChangeStatus(record)} />
                </Space>
            )
        },
        {
            title: '添加日期',
            width: 180,
            key: '4',
            dataIndex: 'createTime',
        },
        {
            title: '描述',
            key: '5',
            dataIndex: 'areaDescription',
        },
    ];
    //打开抽屉
    const showDrawer = () => {
        setOpen(true);
    };
    //关闭抽屉
    const onClose = () => {
        //清空表单数据
        form.setFieldsValue({ areaId: '', areaName: '', createTime: '', areaDescription: '', status: '' })
        setAreaId('')
        setTime('')
        setOpen(false);
    };
    //添加用户信息
    const onFinish = async (values: any) => {
        if (values.areaId) {
            //编辑用户信息
            setLoading(true)
            var res = await service.default.wy.data_update(values)
            if (res.data.code == 200) {
                setLoading(false)
                notification.success({
                    message: '提示',
                    description: '修改成功',
                });
                query(current,pagesize)
                onClose()
            }
        } else {
            setLoading(true)
            Object.assign(values, {
                createTime: time,
                areaId: data.length + 1,
            });
            //添加用户信息
            var res = await service.default.wy.addUser(values)
            if (res.data.code == 200) {
                setLoading(true)
                notification.success({
                    message: '提示',
                    description: '添加成功',
                });
                query(current,pagesize)
                onClose()
            }
        }

    }
    //删除个人用户数据
    const handleDelete = async (record: any) => {
        var res = await service.default.wy.data_delete(record.areaId)
        if (res.data.code == 200) {
            notification.success({
                message: '提示',
                description: '删除成功',
            });
            var list = data.filter((item: any) => item.areaId != record.areaId)
            setData(list)
        }
    }
    //打开抽屉
    const openDrawer = () => {
        var time = formatDate(new Date().getTime())
        setTime(time)
        showDrawer()
    }
    //编辑
    const handleEdit = (record: any) => {
        setAreaId(record.areaId)
        form.setFieldsValue(record)//回显数据
        setTime(record.createTime)//回显时间
        showDrawer()
    }
    //当前页改变时执行分页请求
    const changeSize = (page: any, pageSize: any) => {
        setCurrent(page)
        query(page, pageSize)
    }
    //每页条数改变时执行的分页请求
    const showSizeChange = (current: any, size: any) => {
        stePagesize(size)
        query(current, size)
    }
    return (
        <div className='region'>
            <div className="regionBtns">
                <div>
                    <Button type="primary" onClick={openDrawer}>新增用户</Button>
                </div>
                <div className='regionRev'>
                    <Radio.Group onChange={handleModeChange} value={mode} style={{ marginBottom: 8 }}>
                        <Radio.Button value='全部'>全部</Radio.Button>
                        <Radio.Button value='启用'>启用</Radio.Button>
                        <Radio.Button value='禁用'>禁用</Radio.Button>
                    </Radio.Group>
                    <div className='regionSrech'>
                        <Search
                            placeholder="请输入用户名、账号关键字"
                            enterButton="搜索"
                            onSearch={onSearch}
                        />
                        <div className="regionIcon">
                            <DeleteFilled />
                            <RedoOutlined />
                            <FullscreenOutlined />
                        </div>
                    </div>
                </div>
            </div>
            <div className="regionTable">
                <Table
                    columns={columns}
                    dataSource={data}
                    loading={loading}
                    size='small'
                    pagination={{
                        current: current,
                        pageSize: pagesize,
                        pageSizeOptions: [4, 6, 8, 10],
                        showSizeChanger: true,
                        onChange: changeSize,
                        onShowSizeChange: showSizeChange,
                        total: totals,
                        showTotal:(total:any)=>`共${total}条数据`
                    }} />
            </div>
            <div className="dislog">
                <Drawer title={areaId != '' ? '编辑用户信息' : '新增用户信息'} placement="right" onClose={onClose} open={open}>
                    <Form onFinish={onFinish} form={form}>
                        <Form.Item
                            label="ID"
                            name="areaId"
                            style={{ display: 'none' }}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="区域名称"
                            name="areaName"
                            rules={[{ required: true, message: '请输入!' }]}
                        >
                            <Input disabled={areaId != '' ? true : false} />
                        </Form.Item>
                        <Form.Item
                            label="状态"
                            name="status"
                        >
                            <Select
                                placeholder='请选择'
                                disabled={areaId != '' ? true : false}
                                options={[
                                    { value: 0, label: '启用' },
                                    { value: 1, label: '禁用' },
                                ]}
                            />
                        </Form.Item>
                        <Form.Item
                            label="添加日期"
                            name="createTime"
                        >
                            <span>{time}</span>
                        </Form.Item>
                        <Form.Item
                            label="描述"
                            name="areaDescription"
                        >
                            <TextArea rows={4} />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                {areaId != '' ? '编辑用户信息' : '新增用户信息'}
                            </Button>
                        </Form.Item>
                    </Form>
                </Drawer>
            </div>
        </div>
    );
};

export default Region;